package com.zaofan.mobile.controller;

import com.zaofan.bean.GoodsType;
import com.zaofan.cache.CacheManage;
import com.zaofan.constant.UrlConstant;
import com.zaofan.service.AdImgService;
import com.zaofan.service.GoodsService;
import com.zaofan.service.GoodsTypeService;
import com.zaofan.service.OrderInfoService;
import com.zaofan.service.ProductService;
import com.zaofan.service.remote.RemoteService;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.JsonUtils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/mobile/2.0/index")
public class IndexControllerV2 extends BaseServlet {

	private static final long serialVersionUID = 5884947841079014459L;

	private RemoteService remoteService = new RemoteService();
	private AdImgService adImgService = new AdImgService();
	private ProductService productService = new ProductService();
	private GoodsService goodsService = new GoodsService();
	private GoodsTypeService goodsTypeService = new GoodsTypeService();
	private OrderInfoService orderInfoService = new OrderInfoService();
    private ProductService mProductService = new ProductService();

	/**
	 * app 首页接口 包含全部数据接口
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void home(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("centerAd", CacheManage.centerAd);
			data.put("products", productService.getWeekProducts());
			List<GoodsType> goodsType = goodsTypeService.getTopThreeType();
			data.put("goodsType", goodsType);
			if (goodsType.size() > 0) {
				data.put("goods", goodsService.findByTypeWithPage(goodsType.get(0).getId(), 0, 10));
			} else {
				data.put("goods", new ArrayList<>());
			}
			data.put("sellCount", orderInfoService.getTodaySellCount().intValue());
			JsonUtils.writeSuccessJson("查询成功", data, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询失败", response);
		}
		JsonUtils.writeBeanFailJson("查询失败!!" + ",未知错误", response);
	}

    /**
     * app 首页接口 包含全部数据接口
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void home_new(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("centerAd", CacheManage.centerAd);
            data.put("products", productService.getWeekProductsTwo());
            List<GoodsType> goodsType = goodsTypeService.getTopThreeType();
            data.put("goodsType", goodsType);
            if (goodsType.size() > 0) {
                data.put("goods", goodsService.findByTypeWithPage(goodsType.get(0).getId(), 0, 10));
            } else {
                data.put("goods", new ArrayList<>());
            }
            data.put("sellCount", orderInfoService.getTodaySellCount().intValue());
            JsonUtils.writeSuccessJson("查询成功", data, response);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
        JsonUtils.writeBeanFailJson("查询失败!!" + ",未知错误", response);
    }

    public void goodType(HttpServletRequest request,HttpServletResponse response){
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            List<GoodsType> goodsType = goodsTypeService.getTopThreeType();
            data.put("goodsType", goodsType);
            if (goodsType.size() > 0) {
                data.put("goods", goodsService.findByTypeWithPage(goodsType.get(0).getId(), 0, 10));
            } else {
                data.put("goods", new ArrayList<>());
            }
            JsonUtils.writeSuccessJson("查询成功", data, response);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
        JsonUtils.writeBeanFailJson("查询失败!!" + ",未知错误", response);
    }

    /**
     * app 首页接口 包含全部数据接口
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void home_new_all(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            
            String cityId = request.getParameter("areaId");
            if (cityId == null) {
            	cityId = request.getParameter("cityId");
            }
//            List<Map<String, Object>> products = qr.query("select product.id,name,image,bigImage,shopId from product left join shop on shop.id = product.shopId " +
//                    "where (areaId = ? or coverType = 1) and isQuality = 1",new MapListHandler(),new Object[]{areaId});
            List<Map<String, Object>> productClasses = qr.query("SELECT productclass.id,className,classOrder,productclass.type," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',classImage) as classImage,concat(closetime,' ') as closetime," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',detailImage) as detailImage," +
                    " IF(ISNULL(SUM(dateCount)),0,SUM(dateCount)) AS sellcount FROM productclass " +
                    " LEFT JOIN product ON product.productClassId = productclass.id where productclass.isopen = 1 "
                    + " and productclass.cityId = " + cityId 
                    + " GROUP BY productclass.id  ORDER BY classOrder ", new MapListHandler());
            for (Map<String, Object> item:productClasses){
                item.put("classId",item.get("id"));
            }
//            data.put("quality",products);
            data.put("fourAd",CacheManage.fourAd);
            data.put("centerAd", adImgService.filterByCity(CacheManage.centerAd, Integer.valueOf(cityId)));
            data.put("notice", adImgService.filterByCity(CacheManage.homeNotice, Integer.valueOf(cityId)));
            data.put("productClasses",productClasses);
//            data.put("products", productService.getWeekProductsTwo());
            data.put("products", remoteService.getZhouTaoCan(Integer.valueOf(cityId)));
            data.put("moreProductsTipImage", "http://static.52letsgo.cn/zz/moreProducts.jpg");
            data.put("activityAd", adImgService.findActivityAd(Integer.valueOf(cityId)));
            //签到抽奖

//            data.put("dailyActivity",CacheManage.dailyActivity);

//            data.put("dailyActivity",CacheManage.dailyActivity);

            JsonUtils.writeSuccessJson("查询成功", data, response);

            return;
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
        JsonUtils.writeBeanFailJson("查询失败!!" + ",未知错误", response);
    }

    /**
     * 新版接口
     */
    public void home_info(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            // 获得 城市id
            String cityId = request.getParameter("cityId");

            List<Map<String, Object>> productClasses = qr.query("SELECT productclass.id,className,classOrder,productclass.type," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',classImage) as classImage,concat(closetime,' ') as closetime," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',detailImage) as detailImage," +
                    " CONCAT('"+ UrlConstant.HOST_URL +"',categoryImage) as categoryImage, " +
                    " IF(ISNULL(SUM(dateCount)),0,SUM(dateCount)) AS sellcount FROM productclass " +
                    " LEFT JOIN product ON product.productClassId = productclass.id where productclass.isopen = 1 "
                    + " and productclass.cityId = " + cityId
                    + " GROUP BY productclass.id  ORDER BY classOrder ", new MapListHandler());
            for (Map<String, Object> item:productClasses){
                item.put("classId",item.get("id"));
            }
            //中部广告
            data.put("centerAd", adImgService.filterByCity(CacheManage.centerAd, Integer.valueOf(cityId)));
            //通知走马灯
            data.put("noticeTime", adImgService.filterByCity(CacheManage.homeNotice, Integer.valueOf(cityId)));

            data.put("notice",orderInfoService.findOrderNotice(cityId));
            //首页产品id
            data.put("productClasses",productClasses);
            //周套餐id
            // data.put("products", remoteService.getZhouTaoCan(Integer.valueOf(cityId)));
            //多重选择图片
            //data.put("moreProductsTipImage", "http://static.52letsgo.cn/zz/moreProducts.jpg");
            //弹出框
            data.put("activityAd", adImgService.findActivityAd(Integer.valueOf(cityId)));
            //本周热卖
            data.put("hotProduct",productService.findHotProduct(cityId,0));
            //人气新品
            data.put("newProduct",productService.findNewProduct(cityId));
            //活动
            data.put("dailyActivity",adImgService.filterByCity(CacheManage.dailyActivity, Integer.valueOf(cityId)));
            JsonUtils.writeSuccessJson("查询成功", data, response);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
        JsonUtils.writeBeanFailJson("查询失败!!" + ",未知错误", response);
    }




    /**
	 * app 首页 中部广告位
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void centerAd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			JsonUtils.writeSuccessJson("查询成功", CacheManage.centerAd, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("查询失败", response);
		}
		JsonUtils.writeListFailJson("查询失败!!" + ",未知错误", response);
	}

}
